<template>
	<div class="case_library_wrap">
		<a-space class="search_wrap" direction="vertical" fill>
			<a-space fill align="start" :size="24">
				<a-form-item label="标题">
					<a-input v-model="form.title" placeholder="输入直播标题" />
				</a-form-item>
				<a-form-item class="label_auto" label="ID">
					<a-input
						v-model="form.activityId"
						placeholder="输入直播ID"
						:error="isNaN(Number(form.activityId))"
					/>
				</a-form-item>
				<a-space>
					<a-button type="primary" @click="getActivityList">搜索</a-button>
					<a-button @click="reset">重置</a-button>
				</a-space>
			</a-space>
			<a-space
				v-for="(labelInfo, listIndex) in searchLabelList"
				:key="`list${listIndex}`"
				fill
				align="start"
				:size="24"
			>
				<a-form-item :label="labelInfo.labelName">
					<a-space fill :wrap="true">
						<div
							v-for="(tag, index) in labelInfo.labelList"
							:key="`tag${listIndex}-${index}`"
							class="tag"
							:class="{ active: selectTagList.includes(tag.id) }"
							@click="selectTag(tag)"
						>
							{{ tag.labelName }}
						</div>
					</a-space>
				</a-form-item>
			</a-space>
		</a-space>
		<a-table class="library_list" :columns="activityColumns" :data="activityData" :pagination="false">
			<template #banner="{ record }">
				<img v-if="record.bannerUrl" class="case_banner" :src="record.bannerUrl" alt="" />
			</template>
			<template #createTime="{ record }">
				{{ record.createTime ? dateFormat(record.createTime, 'YYYY-MM-DD HH:mm:ss') : '——' }}
			</template>
			<template #addLibraryTime="{ record }">
				{{ record.addLibraryTime ? dateFormat(record.addLibraryTime, 'YYYY-MM-DD HH:mm:ss') : '——' }}
			</template>
			<template #labelName="{ record }">
				<a-space fill :wrap="true">
					<div
						v-for="(labelName, index) in labelListFilter(record.labelName)"
						:key="`labelTag${index}`"
						class="tag"
					>
						{{ labelName }}
					</div>
				</a-space>
			</template>
			<template #operation="{ record }">
				<div class="operate_wrap">
					<a-trigger
						position="bottom"
						auto-fit-position
						:unmount-on-close="false"
						show-arrow
						:pagination="false"
					>
						<a-button class="operate_btn" type="text">分享</a-button>
						<template #content>
							<div class="table_trigger_popup">
								<div class="share_popup_wrap">
									<img :src="shareQrcodeFilter(record)" alt="" class="qrcode" />
									<div class="activity_share">
										<div class="link">{{ shareUrlFilter(record) }}</div>
										<a-space class="operate_wrap" fill>
											<a-button size="small" @click="copyUrl(record)">复制</a-button>
											<a-button size="small" @click="openUrl(record)">打开</a-button>
										</a-space>
									</div>
								</div>
							</div>
						</template>
					</a-trigger>
					<a-trigger position="bottom" auto-fit-position :unmount-on-close="false" show-arrow>
						<a-button class="operate_btn" type="text"><icon-more /></a-button>
						<template #content>
							<div class="table_trigger_popup">
								<a-space class="operate_wrap" direction="vertical" fill>
									<a-button type="text" long @click="toEditLabel(record)">
										<template #icon>
											<icon-edit />
										</template>
										<template #default>编辑标签</template>
									</a-button>
									<div class="line"></div>
									<a-button
										v-if="record.publishStatus"
										status="danger"
										type="text"
										long
										@click="cancelPublishActivity(record.id, 0)"
									>
										<template #icon>
											<icon-eye-invisible />
										</template>
										<template #default>取消发布</template>
									</a-button>
									<a-button
										v-else-if="!record.isDelete"
										type="text"
										long
										@click="cancelPublishActivity(record.id, 1)"
									>
										<template #icon>
											<icon-eye />
										</template>
										<template #default>发布</template>
									</a-button>
									<a-button status="danger" type="text" long @click="deleteCaseLibriary(record)">
										<template #icon>
											<icon-delete />
										</template>
										<template #default>删除</template>
									</a-button>
								</a-space>
							</div>
						</template>
					</a-trigger>
				</div>
			</template>
		</a-table>
		<div class="account-examine__pagination">
			<span class="total-tips">共{{ total }}条</span>
			<a-pagination v-model:current="current" :total="total" @change="getActivityList" />
		</div>
		<edit-label ref="editLabelRef" @refresh="getActivityList" />
	</div>
</template>
<script lang="ts" setup>
import { ref, computed } from 'vue';
import { label, activity, errors } from '@/api';
import dateFormat from 'ourwill-feutil/common/dateFormat';
import config from '@/api/config';
import { onMounted } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import EditLabel from '@/components/LabelModule/editLabel.vue';
import copyText from 'ourwill-feutil/broswer/copyText';
interface labelItem {
	createTime: number | string;
	createUser: number;
	id: number;
	labelName: string;
	labelParent: number;
	labelType: number;
	labelList?: Array<labelItem>;
}
const labelList = ref<Array<labelItem>>([]);
const getLabelList = async () => {
	try {
		const { data, ok } = await label.getLabelList();
		if (!ok) {
			return;
		}
		labelList.value = data.data || [];
		labelList.value.forEach((e) => {
			if (!e.labelParent) {
				selectTagList.value.push(e.id);
			}
		});
	} catch (error) {
		errors(error);
	}
};
const defaultLabelInfo = {
	createTime: 0,
	createUser: 0,
	id: 0,
	labelName: '全部',
	labelParent: 0,
	labelType: 0,
};
const selectTagList = ref<Array<number>>([]);
const searchLabelList = computed(() => {
	// 这里对获取的列表做数据调整
	let list: Array<labelItem> = [];
	if (!Array.isArray(labelList.value) || !labelList.value.length) {
		return [];
	}
	labelList.value.forEach((e) => {
		// 说明是首位的
		if (!e.labelParent) {
			let info = e;
			let defaultInfo = { ...defaultLabelInfo };
			defaultInfo.id = info.id;
			info.labelList = [defaultInfo];
			list.push(info);
		} else {
			// 说明实在前方id的子集
			let info = list.find((k) => k.id === e.labelParent);
			if (info) {
				let labelList = info.labelList ? [...info.labelList] : [];
				labelList.push(e);
				info.labelList = labelList;
			}
		}
	});
	return list;
});
const selectTag = (tag: labelItem) => {
	// 这里需要判断的逻辑比较多，慢慢来
	// 首先需要判断点击是要取消还是要添加
	let list = [...selectTagList.value];
	if (list.includes(tag.id)) {
		// 这里说明是要取消，需要判断是否点击的全部，全部本身不可取消
		if (!tag.labelParent) {
			return;
		} else {
			// 这里判断当前是否还存在已有列表，如果不存在，则需要添加一下全部
			const allList = labelList.value.filter((e) => e.labelParent === tag.labelParent);
			list = list.filter((e) => {
				return e !== tag.id;
			});
			if (!allList.find((e) => list.includes(e.id))) {
				list.push(tag.labelParent);
			}
		}
	} else {
		// 那么这里说明当前列表不存在，要添加
		// 这里还是要添加判断，因为存在两种情况
		// 第一种，点击的是全部，这个时候，要取消这个全部下面的所有id
		if (!tag.labelParent) {
			const allList = labelList.value.filter((e) => e.labelParent === tag.id);
			list = list.filter((e) => {
				return !allList.find((k) => k.id === e);
			});
			list.push(tag.id);
		} else {
			// 这里说明点击的不是全部，要判断是否存在全部
			if (list.includes(tag.labelParent)) {
				list = list.filter((e) => e !== tag.labelParent);
			}
			list.push(tag.id);
		}
	}
	selectTagList.value = list;
	current.value = 1;
	getActivityList();
};
const form = ref({
	title: '',
	activityId: '',
});
const activityColumns: any = [
	{
		title: 'ID',
		dataIndex: 'id',
		width: 80,
	},
	{
		title: '封面',
		slotName: 'banner',
		width: 150,
	},
	{
		title: '标题',
		dataIndex: 'title',
		width: 343,
	},
	{
		title: '创建时间',
		slotName: 'createTime',
		width: 180,
	},
	{
		title: '添加时间',
		slotName: 'addLibraryTime',
		width: 180,
	},
	{
		title: '标签',
		slotName: 'labelName',
		width: 350,
	},
	{
		title: '操作',
		slotName: 'operation',
		width: 100,
		fixed: 'right',
	},
];
const activityData = ref([]);
const total = ref(0);
const current = ref(1);
const getActivityList = async () => {
	if (isNaN(Number(form.value.activityId))) {
		Message.error('直播间ID输入有误，请输入正确的直播间ID');
		return;
	}
	try {
		const params = {
			pageNum: current.value,
			pageSize: 10,
		};
		let body: any = {};
		// 这里需要判断一下，如果只有存在单独标签的情况下进行传参
		if (selectTagList.value.find((e) => labelList.value.find((label) => e === label.id && label.labelParent))) {
			body.labelList = selectTagList.value;
		}
		if (form.value.title) {
			body.title = form.value.title;
		}
		if (form.value.activityId) {
			body.activityId = Number(form.value.activityId);
		}
		const { data, ok } = await activity.getActivityCaseList(body, params);
		if (!ok) {
			return;
		}
		activityData.value = data.data.records;
		total.value = data.data.total;
	} catch (error) {
		errors(error);
	}
};
const labelListFilter = (labelName: string | null) => {
	return labelName ? labelName.split(',') : [];
};
const shareUrlFilter = (info: any): string => {
	return `${config.host}/${info.id}`;
};
const shareQrcodeFilter = (info: any): string => {
	let link = shareUrlFilter(info);
	return `${config.ssrHost}/qrcode/png/${btoa(link)}.png?s=9`;
};
const copyUrl = (info: any) => {
	const link = shareUrlFilter(info);
	if (copyText(link)) {
		Message.success('复制成功');
	}
};
const openUrl = (info: any) => {
	const link = shareUrlFilter(info);
	window.open(link);
};
const reset = () => {
	current.value = 1;
	form.value.title = '';
	form.value.activityId = '';
	getActivityList();
};
const cancelPublishActivity = async (activityId: number, status: number) => {
	const { ok, data } = await activity.cancelPublishActivity(activityId, status);
	if (!ok) {
		return;
	}
	if (+status === 0) {
		Message.success('取消发布成功');
	} else {
		Message.success('发布成功');
	}
	getActivityList();
};
const deleteCaseLibriary = (activityInfo: { id: number }) => {
	if (!activityInfo || !activityInfo.id) {
		return;
	}
	let loading = false;
	Modal.info({
		title: '提示',
		titleAlign: 'start',
		content: '确认删除吗？',
		hideCancel: false,
		simple: false,
		okLoading: loading,
		onBeforeOk: async () => {
			loading = true;
			try {
				const activityId = activityInfo.id;
				const { ok, data } = await activity.deleteCaseActivity(activityId);
				if (!ok) {
					loading = false;
					return false;
				}
				Message.success(data.msg);
				getActivityList();
				loading = false;
				return true;
			} catch (error) {
				loading = false;
				errors(error);
				return false;
			}
		},
	});
};
onMounted(async () => {
	await getLabelList();
	getActivityList();
});
const editLabelRef = ref();
const toEditLabel = (activityInfo: any) => {
	editLabelRef.value && editLabelRef.value.show(activityInfo);
};
</script>
<style lang="less">
.case_library_wrap {
	width: 100%;
	height: 100%;
	.search_wrap {
		.arco-form-item-label {
			width: 50px;
		}
		.label_auto {
			.arco-form-item-label {
				width: auto;
			}
		}
	}
	.case_banner {
		width: 120px;
	}
	.label_name_wrap {
		width: 100%;
		display: flex;
		flex-flow: row wrap;
		gap: 12px;
	}
	.tag {
		padding: 6px 8px;
		color: #262626;
		border-radius: 4px;
		font-size: 14px;
		line-height: 20px;
		cursor: pointer;
		&.active {
			background-color: #eaeaea;
		}
	}
	.library_list {
		.tag {
			background-color: #eaeaea;
		}
	}
	.operate_wrap {
		display: flex;
		flex-flow: row nowrap;
		align-items: center;
		.operate_btn {
			padding: 0;
			& + .operate_btn {
				margin-left: 10px;
			}
		}
	}
}
.table_trigger_popup {
	padding: 10px;
	background-color: #fff;
	border-radius: 4px;
	box-shadow: 0 2px 8px #00000026;
	.operate_wrap {
		width: 120px;
		.arco-btn {
			text-align: left;
		}
		.line {
			width: 100%;
			height: 1px;
			background-color: #eaeaea;
		}
	}
	.share_popup_wrap {
		width: 250px;
		display: flex;
		flex-flow: row nowrap;
		align-items: stretch;
		.qrcode {
			width: 100px;
			height: 100px;
			display: block;
		}
		.activity_share {
			margin-left: 12px;
			width: calc(100% - 112px);
			display: flex;
			flex-flow: column nowrap;
			justify-content: space-between;
		}
	}
}
</style>
